package com.sydata.job;

import com.sydata.cdrdata.domain.AgentFlowRecord;
import com.sydata.cdrdata.mapper.LinksFieldCdrSettlementMapper;
import com.sydata.cdrdata.service.ILkCdrSettlementService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 每天中午18点30 处理领科流量池结算扣钱
 *
 * @author huangzj@uhuibao.com
 */
@Component
public class CdrSettlementSchedule {

    public static Logger logger = LoggerFactory.getLogger(CdrSettlementSchedule.class);

    @Autowired
    private ILkCdrSettlementService lkCdrSettlementService;

    @Autowired
    LinksFieldCdrSettlementMapper linksFieldCdrSettlementMapper;


    @Async
    @Scheduled(cron = "0 30 18 * * ?") // 每天18点30钟执行
    public void process() {

        // 创建日期格式化对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        // 获取当前日期
        Date date = new Date();
        // 格式化日期
        String formattedDate = sdf.format(date);

        //1、查询领科话单汇总数据 按m渠道、mcc和和日期分组先汇总 然后关联匹配查询出为流量池结算的数据
        List<Map<String, Object>> cdrRecordList = lkCdrSettlementService.getLkCdrRecordList();
        logger.info("------------------【{}】流量结算操作开始------------------------\r\n",formattedDate);
        if (cdrRecordList != null && !cdrRecordList.isEmpty()) {
            logger.info("获取当天入库的汇总查询后的话单数据,汇总后总条数:{}条",cdrRecordList.size());
            for (Map<String, Object> record : cdrRecordList) {
                //supplierId
                String supplierId = record.get("SUPPLIER_ID").toString();
                //channelId
                String channelId = record.get("CHANNEL_ID").toString();
                String mcc = record.get("MCC").toString();
                String simTypeId = record.get("SIM_TYPE_ID").toString();

                //计算除的卡数
                Object iccidNumsObj = record.get("ICCID_NUMS");
                long iccidNums = 0;
                if (iccidNumsObj instanceof BigDecimal) {
                    BigDecimal totalFlowBigDecimal = (BigDecimal) iccidNumsObj;
                    iccidNums = totalFlowBigDecimal.longValue(); // 转换为long，并可能四舍五入
                }

                Object totalFlowObj = record.get("TOTAL_FLOW");
                long totalFlow = 0;
                if (totalFlowObj instanceof BigDecimal) {
                    BigDecimal totalFlowBigDecimal = (BigDecimal) totalFlowObj;
                    totalFlow = totalFlowBigDecimal.longValue(); // 转换为long，并可能四舍五入
                }

                String billDate = record.get("BILL_DATE").toString();

                //2、通过渠道、卡类型、mcc 去查找这个渠道下面国家的单价比例
                Map<String, Object> ratioIno = lkCdrSettlementService.getRatioByMccAndChannel(channelId, simTypeId, mcc);
                if (!ratioIno.isEmpty()) {
                    long ratio = Long.parseLong(ratioIno.get("RATIO").toString());
                    logger.info("国家/地区结算价:{}分", ratio);
                    if (ratio > 0) {

                        // 计算转换后的余额，单位为分  这个ratio字段比如真正值是1，存的是10000000000 （不知道出于啥目的）
                        double roundedBalance = ((double) totalFlow / 1024 / 1024) * (ratio / 10000000000.0);

                        // 直接进行四舍五入，避免中间的字符串转换
                        double roundedBalanceInFen = Math.round(roundedBalance * 100.0);

                        // 记录四舍五入后的余额，单位为分
                        logger.info("四舍五入后的余额（单位：分）-------------------:{}", roundedBalanceInFen);
                        // 如果数据库表设计为存储分，不需要再次转换
                        double updateBalance = roundedBalanceInFen;
                        //扣钱更新余额
                        lkCdrSettlementService.updateChannelBalance(supplierId, channelId, updateBalance);


                        //扣除渠道【蒲游国际】【2024-05-30】【国家】【使用流量123MB】【比例0.007】共扣除金额：2000
                        String totalFlowLog = String.format("%.2f", ((double) totalFlow / 1024 / 1024) );
                        logger.info("扣除记录：【渠道ID：{}】【{}】【mcc:{}】【使用流量{}MB】【比例{}】共扣除金额：{}元", channelId, billDate, mcc, totalFlowLog, ((double) ratio / 10000000000.0), updateBalance/100);
                        logger.info("扣除金额计算公式：  {}元 =({}/1024/1024)*({} / 10000000000)", updateBalance/100, totalFlow, ratio);

                        //记录结算记录
                        String countryCode = ratioIno.get("COUNTRY_CODE").toString();
                        String countryCn = ratioIno.get("COUNTRY_NAME").toString();
                        AgentFlowRecord agentFlowRecord = new AgentFlowRecord();
                        agentFlowRecord.setChannelId(Long.parseLong(channelId));
                        agentFlowRecord.setSuppilerId(Long.parseLong(supplierId));
                        agentFlowRecord.setSimTypeId(Long.parseLong(simTypeId));
                        agentFlowRecord.setCallingCode(countryCode);
                        agentFlowRecord.setCountryCn(countryCn);
                        agentFlowRecord.setSimNumber(iccidNums);
                        agentFlowRecord.setTotalFlow(totalFlow);
                        agentFlowRecord.setRatio(ratio);
                        agentFlowRecord.setMoney((long) updateBalance);
                        agentFlowRecord.setAgentId(0L);
                        agentFlowRecord.setRecordType("MB");

                        String formattedBillDateStr = billDate + ".000"; // 添加毫秒部分

                        agentFlowRecord.setRecordDate(Timestamp.valueOf(formattedBillDateStr));
                        lkCdrSettlementService.insertAgentFlowRecord(agentFlowRecord);
                        logger.info("------------------------------------------\r\n");
                    }
                }
            }
        }
        logger.info("------------------【{}】流量结算操作结束------------------------",formattedDate);
    }

}
